﻿using System;
using System.Collections.Generic;

namespace Hx.ADSyncPlatform.Infrastructure.Tree
{
    public class TreeHelper<T> where T : ITreeNode
    {
        public static List<T> BulidTree(IEnumerable<T> models, Guid rootId)
        {
            var dtoMap = new Dictionary<object, T>();
            foreach (var item in models)
            {
                dtoMap.Add(item.Id, item);
            }
            List<T> result = new List<T>();
            foreach (var item in dtoMap.Values)
            {

                if (Guid.Parse(item.ParentId.ToString()) == rootId)
                {
                    result.Add(item);
                }
                else
                {
                    if (dtoMap.ContainsKey(item.ParentId))
                    {
                        dtoMap[item.ParentId].AddChildren(item);

                        if (dtoMap.ContainsKey(item.Id))
                        {
                            var temp = dtoMap[item.Id];
                            temp.Depth = temp.Depth + 1;
                        }
                    }
                }
            }
            return result;
        }
    }
}
